/*
 *  Copyrigh 2009 Codeinn
 *  This program is distributed under the terms of the GNU General Public License
 *
 *  This file is part of Codeinn.
 *
 *  Codeinn is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Codeinn is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Codeinn.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package http.runnable;

import codeinn.CodeinnMIDlet;
import http.DJangoConnection;
import java.io.IOException;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;

public class Login implements Runnable {

        private String output = null;
        private String url = null;
        private String user = null;
        private String password = null;
        private boolean _hasResult;
        private DJangoConnection dJangoConnection;
        private CodeinnMIDlet codeinnMIDlet;

        public Login(CodeinnMIDlet codeinnMIDlet, String url, String user, String password) {
            this.url = url;
            this.user = user;
            this.password = password;
            this._hasResult = false;
            this.dJangoConnection = new DJangoConnection();
            this.codeinnMIDlet = codeinnMIDlet;
        }

        public void run() {
            try {
                this.output = this.dJangoConnection.httpLogin(this.url, this.user, this.password);
                this.processOutput(this.output);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        private void processOutput(String output) {
            if(this.output.equals(CodeinnMIDlet.MIDLET_RESPONSE_NULL)) {
                Alert alertLoginFailed = new Alert("Login failed", "Incorrect username and/or password", null, AlertType.ERROR);
                alertLoginFailed.setTimeout(Alert.FOREVER);
                this.codeinnMIDlet.switchDisplayable(alertLoginFailed, codeinnMIDlet.getLoginScreen());
            } else {
                this.codeinnMIDlet.setCurrentUser(output);
                this.codeinnMIDlet.getStringItemWelcome().setLabel("Welcome "+output);
                this.codeinnMIDlet.switchDisplayable(null, this.codeinnMIDlet.getFormWelcome());
            }
        }

    }